<template>
  <div v-loading="loading" class="order-detail">
    <el-row v-if="orderData" :gutter="20">
      <!-- 基本信息 -->
      <el-col :span="24">
        <el-card shadow="never" class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="font-semibold">订单基本信息</span>
              <el-tag :type="getStatusType(orderData.status)" size="large">
                {{ orderData.statusName }}
              </el-tag>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="订单号">
                  {{ orderData.orderNo }}
                </el-descriptions-item>
                <el-descriptions-item label="用户信息">
                  {{ orderData.userName }} (ID: {{ orderData.userId }})
                </el-descriptions-item>
                <el-descriptions-item label="联系方式">
                  <div>电话: {{ orderData.userPhone }}</div>
                  <div>邮箱: {{ orderData.userEmail }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="订单金额">
                  <span class="text-red-600 font-semibold">¥{{ orderData.totalAmount }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="支付金额">
                  <span class="text-green-600 font-semibold">¥{{ orderData.payAmount }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="支付方式">
                  {{ orderData.paymentMethod || "未支付" }}
                </el-descriptions-item>
                <el-descriptions-item label="下单时间">
                  {{ formatDateTime(orderData.createTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="支付时间">
                  {{ formatDateTime(orderData.paymentTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="发货时间">
                  {{ formatDateTime(orderData.shipTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="完成时间">
                  {{ formatDateTime(orderData.completeTime) }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 收货地址 -->
      <el-col :span="12">
        <el-card shadow="never" class="mb-4">
          <template #header>
            <span class="font-semibold">收货地址</span>
          </template>
          <div class="address-info">
            <p><strong>收货人：</strong>{{ orderData.shippingAddress.receiverName }}</p>
            <p><strong>联系电话：</strong>{{ orderData.shippingAddress.receiverPhone }}</p>
            <p>
              <strong>收货地址：</strong>
              {{ orderData.shippingAddress.province }}
              {{ orderData.shippingAddress.city }}
              {{ orderData.shippingAddress.district }}
              {{ orderData.shippingAddress.detail }}
            </p>
          </div>
        </el-card>
      </el-col>

      <!-- 物流信息 -->
      <el-col :span="12">
        <el-card shadow="never" class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="font-semibold">物流信息</span>
              <el-button
                v-if="orderData.logistics.trackingNumber"
                size="small"
                type="primary"
                :loading="logisticsLoading"
                @click="refreshLogistics"
              >
                刷新物流
              </el-button>
            </div>
          </template>
          <div v-if="orderData.logistics.company">
            <p><strong>物流公司：</strong>{{ orderData.logistics.company }}</p>
            <p><strong>快递单号：</strong>{{ orderData.logistics.trackingNumber }}</p>
            <p>
              <strong>物流状态：</strong>
              <el-tag :type="getLogisticsStatusType(orderData.logistics.status)">
                {{ orderData.logistics.status }}
              </el-tag>
            </p>

            <!-- 物流轨迹 -->
            <div v-if="logisticsInfo.tracks && logisticsInfo.tracks.length > 0" class="mt-4">
              <h4 class="mb-2">物流轨迹</h4>
              <el-timeline>
                <el-timeline-item
                  v-for="(track, index) in logisticsInfo.tracks"
                  :key="index"
                  :timestamp="formatDateTime(track.time)"
                  placement="top"
                >
                  <div>
                    <strong>{{ track.status }}</strong>
                    <p class="text-gray-600">{{ track.description }}</p>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
          <div v-else class="text-gray-500">暂无物流信息</div>
        </el-card>
      </el-col>

      <!-- 商品明细 -->
      <el-col :span="24">
        <el-card shadow="never" class="mb-4">
          <template #header>
            <span class="font-semibold">商品明细</span>
          </template>
          <el-table :data="orderData.items" style="width: 100%">
            <el-table-column label="商品图片" width="100">
              <template #default="{ row }">
                <el-image
                  :src="row.productImage"
                  :preview-src-list="[row.productImage]"
                  fit="cover"
                  style="width: 60px; height: 60px"
                  :hide-on-click-modal="true"
                  preview-teleported
                  scale="0.8"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="sku" label="SKU" width="150" />
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="{ row }"> ¥{{ row.unitPrice }} </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="totalPrice" label="小计" width="100">
              <template #default="{ row }">
                <span class="font-semibold text-red-600">¥{{ row.totalPrice }}</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 金额汇总 -->
          <div class="amount-summary mt-4">
            <el-row justify="end">
              <el-col :span="8">
                <div class="summary-item">
                  <span>商品总额：</span>
                  <span class="amount">¥{{ orderData.totalAmount }}</span>
                </div>
                <div class="summary-item">
                  <span>实付金额：</span>
                  <span class="amount final-amount">¥{{ orderData.payAmount }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <!-- 备注信息 -->
      <el-col :span="24">
        <el-card shadow="never" class="mb-4">
          <template #header>
            <span class="font-semibold">备注信息</span>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="remark-section">
                <h4>用户备注</h4>
                <p class="remark-content">{{ orderData.remark || "无" }}</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="remark-section">
                <h4>管理员备注</h4>
                <div class="admin-remark">
                  <p class="remark-content">
                    {{ orderData.adminRemark || "无" }}
                  </p>
                  <el-button size="small" type="primary" @click="editAdminRemark"> 编辑备注 </el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 操作按钮 -->
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <span class="font-semibold">订单操作</span>
          </template>
          <div class="operation-buttons">
            <el-button v-if="orderData.status === 3" type="success" @click="handleShip"> 立即发货 </el-button>
            <el-button
              v-if="orderData.status <= 3 && orderData.status !== 6"
              type="warning"
              @click="handleCancel"
            >
              取消订单
            </el-button>
            <el-button v-if="orderData.status === 4" type="primary" @click="handleComplete">
              确认完成
            </el-button>
            <el-button @click="viewOrderLogs">查看日志</el-button>
            <el-button @click="printOrder">打印订单</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 管理员备注编辑模态框 -->
    <el-dialog v-model="showRemarkModal" title="编辑管理员备注" width="500px">
      <el-input
        v-model="adminRemark"
        type="textarea"
        :rows="4"
        placeholder="请输入管理员备注"
        maxlength="200"
        show-word-limit
      />
      <template #footer>
        <el-button @click="showRemarkModal = false">取消</el-button>
        <el-button type="primary" @click="saveAdminRemark">保存</el-button>
      </template>
    </el-dialog>

    <!-- 发货模态框 -->
    <el-dialog v-model="showShipModal" title="订单发货" width="600px">
      <el-form ref="shipFormRef" :model="shipForm" :rules="shipRules" label-width="100px">
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-select v-model="shipForm.logisticsCompany" placeholder="请选择物流公司">
            <el-option label="顺丰速运" value="顺丰速运" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
            <el-option label="圆通速递" value="圆通速递" />
            <el-option label="百世快递" value="百世快递" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="trackingNumber">
          <el-input v-model="shipForm.trackingNumber" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="发货备注">
          <el-input
            v-model="shipForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入发货备注（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showShipModal = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确认发货</el-button>
      </template>
    </el-dialog>

    <!-- 订单日志模态框 -->
    <el-dialog v-model="showLogsModal" title="订单日志" width="700px">
      <el-timeline v-if="orderLogs.length > 0">
        <el-timeline-item
          v-for="log in orderLogs"
          :key="log.id"
          :timestamp="formatDateTime(log.createTime)"
          placement="top"
        >
          <el-card>
            <h4>{{ log.operationName }}</h4>
            <p>操作人：{{ log.operatorName }}</p>
            <p v-if="log.remark">备注：{{ log.remark }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="暂无操作日志" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineEmits } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Picture } from "@element-plus/icons-vue";
import {
  getOrderDetail,
  updateOrderStatus,
  updateOrderRemark,
  shipOrder,
  getOrderLogs,
  getLogisticsInfo,
  cancelOrder,
  OrderStatus
} from "@/api/order-management";

const props = defineProps<{
  orderId: number;
}>();

const emit = defineEmits<{
  refresh: [];
}>();

// 响应式数据
const loading = ref(false);
const logisticsLoading = ref(false);
const orderData = ref(null);
const logisticsInfo = ref({ tracks: [] });
const orderLogs = ref([]);

// 模态框控制
const showRemarkModal = ref(false);
const showShipModal = ref(false);
const showLogsModal = ref(false);

// 备注编辑
const adminRemark = ref("");

// 发货表单
const shipFormRef = ref();
const shipForm = reactive({
  logisticsCompany: "",
  trackingNumber: "",
  remark: ""
});

const shipRules = {
  logisticsCompany: [{ required: true, message: "请选择物流公司", trigger: "change" }],
  trackingNumber: [{ required: true, message: "请输入快递单号", trigger: "blur" }]
};

// 获取订单详情
const getOrderDetailData = async () => {
  loading.value = true;
  try {
    const res = await getOrderDetail(props.orderId);
    if (res.code === 200) {
      orderData.value = res.data;
      adminRemark.value = res.data.adminRemark || "";

      // 如果有物流信息，获取物流轨迹
      if (res.data.logistics?.trackingNumber) {
        await getLogisticsData();
      }
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
    ElMessage.error("获取订单详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取物流信息
const getLogisticsData = async () => {
  try {
    const res = await getLogisticsInfo(props.orderId);
    if (res.code === 200) {
      logisticsInfo.value = res.data;
    }
  } catch (error) {
    console.error("获取物流信息失败:", error);
  }
};

// 刷新物流信息
const refreshLogistics = async () => {
  logisticsLoading.value = true;
  try {
    await getLogisticsData();
    ElMessage.success("物流信息已更新");
  } catch (error) {
    ElMessage.error("刷新物流信息失败");
  } finally {
    logisticsLoading.value = false;
  }
};

// 获取状态标签类型
const getStatusType = status => {
  const statusTypes = {
    1: "warning", // 待付款
    2: "info", // 已付款
    3: "danger", // 待发货
    4: "primary", // 已发货
    5: "success", // 已完成
    6: "info" // 已取消
  };
  return statusTypes[status] || "info";
};

// 获取物流状态标签类型
const getLogisticsStatusType = status => {
  const statusTypes = {
    运输中: "primary",
    派送中: "warning",
    已签收: "success",
    异常: "danger"
  };
  return statusTypes[status] || "info";
};

// 格式化日期时间
const formatDateTime = dateStr => {
  if (!dateStr) return "-";
  return new Date(dateStr).toLocaleString("zh-CN");
};

// 编辑管理员备注
const editAdminRemark = () => {
  showRemarkModal.value = true;
};

// 保存管理员备注
const saveAdminRemark = async () => {
  try {
    const res = await updateOrderRemark(props.orderId, adminRemark.value);
    if (res.code === 200) {
      ElMessage.success("备注更新成功");
      showRemarkModal.value = false;
      orderData.value.adminRemark = adminRemark.value;
      emit("refresh");
    }
  } catch (error) {
    console.error("更新备注失败:", error);
    ElMessage.error("更新备注失败");
  }
};

// 发货处理
const handleShip = () => {
  Object.assign(shipForm, {
    logisticsCompany: "",
    trackingNumber: "",
    remark: ""
  });
  showShipModal.value = true;
};

// 确认发货
const confirmShip = async () => {
  const valid = await shipFormRef.value?.validate();
  if (!valid) return;

  try {
    const res = await shipOrder(props.orderId, shipForm);
    if (res.code === 200) {
      ElMessage.success("发货成功");
      showShipModal.value = false;
      await getOrderDetailData();
      emit("refresh");
    } else {
      ElMessage.error(res.message || "发货失败");
    }
  } catch (error) {
    console.error("发货失败:", error);
    ElMessage.error("发货失败");
  }
};

// 取消订单
const handleCancel = () => {
  ElMessageBox.prompt("请输入取消原因", "取消订单", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPlaceholder: "请输入取消原因"
  }).then(async ({ value }) => {
    try {
      const res = await cancelOrder(props.orderId, value);
      if (res.code === 200) {
        ElMessage.success("订单取消成功");
        await getOrderDetailData();
        emit("refresh");
      }
    } catch (error) {
      console.error("取消订单失败:", error);
      ElMessage.error("取消订单失败");
    }
  });
};

// 确认完成订单
const handleComplete = async () => {
  try {
    const res = await updateOrderStatus(props.orderId, OrderStatus.COMPLETED, "管理员确认完成");
    if (res.code === 200) {
      ElMessage.success("订单已完成");
      await getOrderDetailData();
      emit("refresh");
    }
  } catch (error) {
    console.error("完成订单失败:", error);
    ElMessage.error("完成订单失败");
  }
};

// 查看订单日志
const viewOrderLogs = async () => {
  try {
    const res = await getOrderLogs(props.orderId);
    if (res.code === 200) {
      orderLogs.value = res.data || [];
      showLogsModal.value = true;
    }
  } catch (error) {
    console.error("获取订单日志失败:", error);
    ElMessage.error("获取订单日志失败");
  }
};

// 打印订单
const printOrder = () => {
  window.print();
};

// 初始化
onMounted(() => {
  if (props.orderId) {
    getOrderDetailData();
  }
});
</script>

<style scoped>
/* 打印样式 */
@media print {
  .operation-buttons,
  .card-header .el-tag,
  .el-button {
    display: none !important;
  }

  .order-detail {
    padding: 0;
  }

  .el-card {
    border: 1px solid #ddd !important;
    box-shadow: none !important;
  }
}

.order-detail {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.address-info p {
  margin: 8px 0;
  line-height: 1.6;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 24px;
  color: #909399;
  background: #f5f7fa;
}

.amount-summary {
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.summary-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-item .amount {
  font-weight: bold;
  color: #606266;
}

.summary-item .final-amount {
  font-size: 16px;
  color: #f56c6c;
}

.remark-section {
  margin-bottom: 16px;
}

.remark-section h4 {
  margin-bottom: 8px;
  font-size: 14px;
  color: #303133;
}

.remark-content {
  min-height: 40px;
  padding: 12px;
  margin: 8px 0;
  line-height: 1.6;
  color: #606266;
  background: #f8f9fa;
  border-radius: 4px;
}

.admin-remark {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
</style>
